package dao

import (
	"device/model"
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"log"
)

var gdb *gorm.DB
var GatawayAddr = "192.168.146.11:9000"
var KeyCenter = "192.168.146.12:8990"

//var ServicePort = "8080"

type SQLConfig struct {
	Username string
	Password string
	Addr     string
	Database string
}

var MysqlConfig = SQLConfig{
	Username: "bt_go",
	Password: "07ZjxQG87NTO9hUL",
	Addr:     "175.178.40.245:3309",
	Database: "SPA",
}

func init() {
	var err error
	cfg := MysqlConfig
	gdb, err = gorm.Open(mysql.Open(fmt.Sprintf("%s:%s@tcp(%s)/%s?parseTime=True", cfg.Username, cfg.Password, cfg.Addr, cfg.Database)), &gorm.Config{
		Logger: logger.Default.LogMode(logger.Info),
	})
	if err != nil {
		log.Println(err)
		return
	}
	fmt.Println(gdb.CreateBatchSize)
	//gdb.AutoMigrate(&model.UserInfo{}, &model.Game{})
	//gdb.AutoMigrate(&model.Way{}, &model.Game{})
	//gdb.AutoMigrate(&model.CertificateInfo{})
}

func IfDeviceExcite(d *model.DeviceInfo) (bool, string) {
	device := new(model.DeviceInfo)
	gdb.Where("id = ?", d.ID).First(device)
	if device.Token != d.Token || device.ID == 0 {
		return false, "设备匹配失败"
	}
	return true, ""
}

func SetCertificate(token string, pem string) {
	cer := new(model.CertificateInfo)
	cer.Token = token
	cer.Certificate = pem
	gdb.Create(cer)
}

func GetCertificate(token string) *model.CertificateInfo {
	Certificate := new(model.CertificateInfo)
	gdb.Where("token = ?", token).First(Certificate)
	return Certificate
}

func AutoMigrate(in interface{}) {
	gdb.AutoMigrate(in)
}
